package tx.config;

import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration;
import org.springframework.transaction.interceptor.*;

import java.util.Collections;
import java.util.Properties;

/**
 * 通过 AOP 切面设置全局事务，拦截 service 包下面所有方法
 * AOP 术语：通知（Advice）、连接点（Joinpoint）、切入点（Pointcut)、切面（Aspect）、目标(Target)、代理(Proxy)、织入（Weaving）
 *
 * @see EnableAspectJAutoProxy 会向容器注入 AnnotationAwareAspectJAutoProxyCreator
 * @see EnableTransactionManagement 会向容器注入 InfrastructureAdvisorAutoProxyCreator
 * 同时使用时，最终会使用 AnnotationAwareAspectJAutoProxyCreator 来生成代理
 * @see org.springframework.aop.config.AopConfigUtils
 */
@EnableAspectJAutoProxy
// @Configuration(proxyBeanMethods = false)
public class TransactionAdviceConfig {

    /* 定义切点变量：拦截 **.service 包下所有类的所有方法,返回值类型任意的方法 */
    private static final String AOP_POINTCUT_EXPRESSION = "execution (* **.service.*.*(..))";

    /**
     * 利用 AspectJExpressionPointcut 设置切面=切点+通知（写成内部 Bean 的方式），需要 @EnableAspectJAutoProxy
     * 不需要 @EnableTransactionManagement
     */
    @Bean
    public Advisor txAdviceAdvisor(TransactionManager transactionManager) {
        /* 声明切点的面
         * 切面（Aspect）：切面就是通知和切入点的结合。通知和切入点共同定义了关于切面的全部内容——它的功能、在何时和何地完成其功能。
         * */
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        /* 声明和设置需要拦截的方法,用切点语言描写 */
        pointcut.setExpression(AOP_POINTCUT_EXPRESSION);
        /* 设置切面= 切点pointcut + 通知TxAdvice */
        return new DefaultPointcutAdvisor(pointcut, txAdvice(transactionManager));
    }

    /**
     * 不添加到 IOC 容器中，不覆盖 Spring 提供的 transactionInterceptor
     */
    // @Bean("transactionInterceptor")
    public TransactionInterceptor txAdvice(TransactionManager transactionManager) {
        /*事务管理规则，声明具备事务管理的方法名*/
        NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
        source.addTransactionalMethod("add*", requiredTransactionRule());
        source.addTransactionalMethod("save*", requiredTransactionRule());
        source.addTransactionalMethod("insert*", requiredTransactionRule());
        source.addTransactionalMethod("delete*", requiredTransactionRule());
        source.addTransactionalMethod("update*", requiredTransactionRule());
        source.addTransactionalMethod("exec*", requiredTransactionRule());
        source.addTransactionalMethod("set*", requiredTransactionRule());
        source.addTransactionalMethod("get*", readOnlyTransactionRule());
        source.addTransactionalMethod("query*", readOnlyTransactionRule());
        source.addTransactionalMethod("find*", readOnlyTransactionRule());
        source.addTransactionalMethod("list*", readOnlyTransactionRule());
        source.addTransactionalMethod("count*", readOnlyTransactionRule());
        source.addTransactionalMethod("is*", readOnlyTransactionRule());
        return new TransactionInterceptor(transactionManager, source);
    }

    /**
     * 当前存在事务就使用当前事务，当前不存在事务就创建一个新的事务 {@link org.springframework.transaction.annotation.Propagation#REQUIRED}
     */
    private RuleBasedTransactionAttribute requiredTransactionRule() {
        RuleBasedTransactionAttribute required = new RuleBasedTransactionAttribute();
        /* 添加对所有 EXCEPTON 异常进行事务回滚 */
        required.setRollbackRules(Collections.singletonList(new RollbackRuleAttribute(Exception.class)));
        required.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        /* 设置事务失效时间，如果超过 5 秒，则回滚事务 */
        required.setTimeout(5);
        return required;
    }

    /**
     * 只读事务 {@link org.springframework.transaction.annotation.Propagation#NOT_SUPPORTED}
     */
    private RuleBasedTransactionAttribute readOnlyTransactionRule() {
        RuleBasedTransactionAttribute readOnly = new RuleBasedTransactionAttribute();
        /*设置当前事务是否为只读事务，true为只读*/
        readOnly.setReadOnly(true);
        readOnly.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);
        return readOnly;
    }

    // =============================================================================================

    /**
     * 不需要 @EnableAspectJAutoProxy 和 @EnableTransactionManagement
     */
    // @Bean
    public BeanNameAutoProxyCreator txProxy() {
        BeanNameAutoProxyCreator creator = new BeanNameAutoProxyCreator();
        // 此处这个 BeanName 一定要对应上
        creator.setInterceptorNames("transactionInterceptor");
        creator.setBeanNames("*Service", "*ServiceImpl");
        // creator.setProxyTargetClass(true);
        return creator;
    }

    /**
     * 创建事务通知，名为 transactionInterceptor，覆盖 Spring 提供的，否则两个都会注册进容器里面去
     *
     * @see ProxyTransactionManagementConfiguration#transactionInterceptor(TransactionAttributeSource)
     */
    // @Bean(name = "transactionInterceptor")
    public TransactionInterceptor transactionInterceptor(TransactionManager transactionManager) {
        TransactionInterceptor interceptor = new TransactionInterceptor();
        // 设置事务管理器，去管理这个 Bean 的事务关系
        interceptor.setTransactionManager(transactionManager);
        // 设置事务相关的属性：transactionAttributes
        Properties transactionAttributes = new Properties();
        // transactionAttributes.setProperty("get*", "PROPAGATION_NOT_SUPPORTED,-Exception,readOnly");
        // transactionAttributes.setProperty("add*", "PROPAGATION_REQUIRED,-Exception");
        // transactionAttributes.setProperty("save*", "PROPAGATION_REQUIRED,-Exception");
        // transactionAttributes.setProperty("update*", "PROPAGATION_REQUIRED,-Exception");
        // transactionAttributes.setProperty("delete*", "PROPAGATION_REQUIRED,-Exception");
        transactionAttributes.setProperty("*", "PROPAGATION_REQUIRED");
        interceptor.setTransactionAttributes(transactionAttributes);
        return interceptor;
    }
}
